﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfPractice.MVVM
{
    public class DelegateCommand : ICommand
    {
        //第一个参数是需要执行的方法，第二个方法是自定义判断能否执行的方法
        //如果前台定义了CommandParameter，实例化DelegateCommand的方法也需要Object参数就能在后台接收到
        public DelegateCommand(Action<object?> action, Func<object?, bool> func = null)
        {
            this.ExecuteAction = action;
            this.CanExecuteFunc = func;
        }
        public DelegateCommand(Action action, Func<bool> func = null)
        {
            this.ExecuteActionNoPara = action;
            this.CanExecuteFuncNoPara = func;
        }
        private Action<object?> ExecuteAction { get; set; }
        private Func<object?, bool> CanExecuteFunc { get; set; }
        private Action ExecuteActionNoPara { get; set; }
        private Func<bool> CanExecuteFuncNoPara { get; set; }

        public event EventHandler? CanExecuteChanged;
        //如果前台定义了CommandParameter，这个方法就会接收到parameter，否则为null
        public bool CanExecute(object? parameter = null)
        {
            if (parameter != null)
            {
                return CanExecuteFunc == null ? true : CanExecuteFunc.Invoke(parameter);
            }
            return CanExecuteFuncNoPara == null ? true : CanExecuteFuncNoPara.Invoke();
        }
        //如果前台定义了CommandParameter，这个方法就会接收到parameter，否则为null
        public void Execute(object? parameter = null)
        {
            if (parameter != null) ExecuteAction?.Invoke(parameter);
            else ExecuteActionNoPara?.Invoke();
        }
    }
}
